<template>
  <div class="wrapper">
    <div>
      <p class="upload-tips" v-show="isShowBtn" v-if="screenObjs.androidVersion < 5">
        <icon type="info-circle"></icon>
        提示：如拍照上传失败，请从相册里选取照片上传
      </p>
      <!--图片上传区-->
      <div class="image-container" v-for="(item, index) in attachments" :key="'a' + index">
        <div class="image-main" :style="{padding: mainPadding}">
          <h3 class="imageTitle">
            <span class="text">{{item.groupName}} <i v-show="item.isRequired == 'Y'">*</i></span>

          </h3>
          <p class="image-desc">
            {{item.groupDesc}}
          </p>
          <!--上传组件区-->
          <div class="upload-container">
            <v-upload :files="item.files"
                      :groupCode="item.groupCode"
                      :isDisabled="isDisabled"
                      :isFinished="isFinished"
                      :accessTokenObj="accessTokenObj"
                      v-on:accessToken="getToken"
                      :screenObjs="screenObjs"
                      :waybillNo="waybillNo">
            </v-upload>
          </div>
        </div>
        <!--分割区-->
        <div class="split vux-1px-tb" v-if="index < attachments.length - 1">

        </div>
      </div>

      <!-- <div class="image-container vux-1px-b">
         <h3 class="imageTitle vux-1px-b">
           <span class="text">受损货物 <i>*</i></span>
           <span class="count" v-show="attachments.length > 0">已上传{{attachments.length}}张图片</span>
         </h3>
         <p class="image-desc">
           资料要求：需体现受损的货物，包括数量和损坏情况
         </p>
         <div class="upload-container">
           <v-upload
             :files="attachments"
             :waybillNo="waybillNo">
           </v-upload>
         </div>
       </div>-->
      <!--按钮区-->
      <div class="step-next vux-1px-t" v-show="isShowBtn">

        <div class="navigation" >
          <!--<router-link :to="{name: 'info', params: waybillNo}" replace class="back" tag="div">
            《 报案信息
          </router-link>
          <router-link :to="{name: 'progress', params: waybillNo}" replace class="back" tag="div">
            理赔进度 》
          </router-link>-->
          <div class="back" @click="goToInfo">
            《 报案信息
          </div>
          <div class="back" @click="goToProgress">
            理赔进度 》
          </div>
        </div>
        <x-button
          type="primary"
          action-type="button"
          :disabled="isDisabled"
          @click.native="subApproveRequest">
          提交
        </x-button>
      </div>
    </div>

  </div>
</template>

<script>
  import {XButton, Group, XInput, Icon } from 'vux'
  import Upload  from './upload/upload'
  import axios from '../api/config'
  import {_getAttachments, _postApproveRequest, _getAccessToken} from '../api/api'
  export default {
    data() {
      return {
        caseType: 'DRIVER',
        waybillNo: '',
        attachments: [
        ],
        claimStatus: '',
        isShowBtn: false,

        accessTokenObj: {},

        screenObjs: {}
      }
    },
    computed: {
      notPostMsg() {
        let str = ''
        this.attachments.every((item, index) => {
          if(item.isRequired == 'Y') {
            if(item.files.length < 1) {
              str = item.groupName
              return false
            }
            return true
          }
        })
        return str
      },
      isDisabled() {
        if(this.claimStatus == 'DRAFT_MANUAL' ||
          this.claimStatus == 'DRAFT_AUTO' ||
          this.claimStatus == 'REJECT_TO_NETWORK' ||
          this.claimStatus == 'REJECT_TO_ENTPR'
        ) {
          return false
        } else {
          return true
        }
      },
      isFinished() {
        if(this.claimStatus == 'FINISHED') {
          return true
        } else {
          return false
        }
      },
      mainPadding() {
        if(this.screenObjs.androidVersion < 4.4) {
          return '8px 0 10px 14px'
        } else {
          return '8px 14px 10px'
        }
      }
    },
    components: {
      XButton,
      Group,
      XInput,
      Icon,
      'v-upload': Upload
    },
    mounted() {
      this.getAttachments()
      this.getAccessTokens()
      this.getPageWidths()
      this.changeInput()
    },
    methods: {
      getAttachments() {    //查询理赔附件组
        this.waybillNo = this.$route.params.waybillNo
        if (this.waybillNo) {
          let parameter = JSON.parse(sessionStorage.parameter)
          this.caseType = parameter.caseType
          let url = _getAttachments(this.waybillNo, this.caseType)
          this.isShowBtn = false
          this.$vux.loading.show({
            text: '加载中...'
          })
          axios.get(url)
            .then((res) => {
              this.$vux.loading.hide()
              this.isShowBtn = true
              let resData = res.data.data
              this.attachments = resData.attachments || []
              this.claimStatus = resData.claimStatus
            })
        } else {
          this.$vux.toast.show({
            text: '未找到运单号',
            type: 'warn'
          })
        }
      },
      subApproveRequest(){
        if(!this.notPostMsg) { //如果全部上传 发起提交核损请求
          if(!this.isDisabled) { //如果有编辑权限
            let callbackUrl = JSON.parse(sessionStorage.getItem("parameter")).callbackUrl
            let url = `/claims/${this.waybillNo}/approveRequest?callbackUrl=${callbackUrl}`
            axios.post(url)
              .then((res) => {
                let resMeta = res.data.meta
                if(resMeta.code == 'SUCCESS') {
                  this.$toast(resMeta.message, 'success')
                  setTimeout(() => {
                    this.$router.replace({name:'progress',params:this.$route.params})
                  }, 400)
                }
              })
          }
        } else {               //如果还有未上传的选项
          this.$toast('请上传' + this.notPostMsg)
        }
      },
      getToken (val) {
        console.log(val)
        let url = _getAccessToken(this.waybillNo)
        axios.get(url)
          .then((res) => {
            let resData = res.data.data
            this.accessTokenObj = resData
            window.sessionStorage.accessToken = JSON.stringify(resData)
            console.log(this.accessTokenObj)
          })
      },
      getAccessTokens() {
        let _Now = new Date().getTime() / 1000
        if(window.sessionStorage.accessToken) {
          this.accessTokenObj = JSON.parse(window.sessionStorage.accessToken)
          console.log(this.accessTokenObj)
          if(_Now + 3 > this.accessTokenObj.expire) { //过期了
            console.log('过期了')
            this.getToken()
          } else {
            console.log('没过期')
            console.log(this.accessTokenObj)
          }
        } else {
          console.log('这是父级组件的...')
          this.getToken()
        }
      },
      changeInput() {
        setTimeout(() => {
          let _inputs = document.getElementsByTagName('input')
          for(let i = 0; i < _inputs.length; i++) {
            _inputs[i].setAttribute('accept', 'image/*')
            _inputs[i].setAttribute('capture', 'camera')
            /*_inputs[i].setAttribute('multiple', 'multiple')*/
          }
        }, 500)
      },
      /*获取屏幕宽高*/
      getPageWidths() {
        this.screenObjs = JSON.parse(window.sessionStorage.screenObj)
        console.log(this.screenObjs)
      },

      goToInfo() {
        this.$router.replace({
          name: 'info',
          params: {waybillNo: this.waybillNo}
        })
      },
      goToProgress() {
        this.$router.replace({
          name: 'progress',
          params: {waybillNo: this.waybillNo}
        })
      }
    }
  }
</script>

<style lang="less" rel="stylesheet/less" scoped>
  @tipColor: #f90000;
  @tipIconColor: #999;
  @import '~vux/src/styles/1px.less';
  @import "../common/flexBox.less";

  .upload-tips {
    margin-top: 12px;
    font-size: 12px;
    color: @tipIconColor;
    padding-left: 14px;
    .weui-icon {
      font-size: 16px;
      color: @tipIconColor;
      vertical-align: text-bottom;
    }
  }
  .image-container {
    font-size: 14px;
    .image-main {
      .imageTitle {
        .flexBox;
        .flexContentSpace;
        padding-bottom: 2px;
        color: @tipColor;
        .text {
          i {
            font-style: normal;
          }
        }
        .count {
          font-size: 14px;
          color: #ef0d0d;
        }
      }
      .image-desc {
        color: @tipIconColor;
      }
    }
    .split {
      height: 13px;
      background-color: #ecebeb;
    }
  }

  .step-next {
    padding: 14px 16px 25px;
    text-align: center;
    .navigation {
      .flexBox;
      .flexContentSpace;
      margin-bottom: 20px;
      .back{
        font-size: 14px;
        color: @tipColor;
      }
    }
  }
</style>
